package com.examplemartin.jpademo.util;

import com.examplemartin.jpademo.annotation.EntityCheck;
import com.examplemartin.jpademo.bean.AjaxResult;

import java.lang.reflect.Field;

public class EntityCheckUtil {
    public static AjaxResult check(Object obj){
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            EntityCheck annotation = field.getAnnotation(EntityCheck.class);
            if(annotation!=null){
                if(annotation.required()){
                    field.setAccessible(true);
                    try {
                        Object o = field.get(obj);
                        if(o==null){
                            return AjaxResult.fail(500,annotation.errRequired());
                        }
                        if(!isNumberObject(o)){
                            if(o.toString().trim().length()<=0){
                                return AjaxResult.fail(500,annotation.errRequired());
                            }
                        }

//                        判断是否为数字
                        if(annotation.isNumber()){
                            if(!isNumberObject(o)){
                                return AjaxResult.fail(500,annotation.errIsNumber());
                            }

                            // 判断最小值
                            if(annotation.minVal()){
                                if(Double.valueOf(o.toString())<annotation.minV()){
                                    return AjaxResult.fail(500,annotation.errMinValue());
                                }
                            }

                            // 判断最大值
                            if(annotation.maxVal()){
                                if(Double.valueOf(o.toString())>annotation.maxV()){
                                    return AjaxResult.fail(500,annotation.errMaxValue());
                                }
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return AjaxResult.success(200,"",null);
    }

    /**
     * 检查对象是否是数字类型
     * @param object
     * @return
     */
    public static boolean isNumberObject(Object object){
        if(object instanceof Integer)return true;
        if(object instanceof Long)return true;
        if(object instanceof Float)return true;
        if(object instanceof Double)return true;
        return false;
    }
}
